<template>
  <Container class="bargain-rules">
    <div slot="header" class="container-header title title-center">工厂特价
      <Button
        size="large"
        class="fl btn-back"
        icon="ios-arrow-back"
        @click="jumpPrevPage"
      >返回</Button>
    </div>
    <edit ref="edit" :form="$store.state.bargain.form" />
    <div slot="footer" class="container-footer bg-white">
      <Button type="primary" size="large" class="ml" :loading="loading" @click="onShowList()">下一步</Button>
    </div>
    <Loader :status="status" @refresh="getDetailData" />
    <!-- <storeList ref="storeEdit"></storeList> -->
  </Container>
</template>
<script>
import edit from './edit/DefaultEditItem'
// import storeList from './edit/StoreListItem'
import { mapGetters, mapState } from 'vuex'
import { formatDate } from '@/views/sales/common/TableSaleMethods'
import { preFixPath } from '@/util'
export default {
  components: {
    edit
    // storeList
  },
  data () {
    return {
      id: this.$route.query.id || '',
      type: this.$route.query.type || '',
      isEmpty: false, // 是否清空数据
      isSave: true, // 是否保存数据
      loading: false,
      status: 'pass'
    }
  },
  computed: {
    ...mapGetters([
      'bargainSelected',
      'allDistributor',
      'bargainIsCurrencyNum',
      'bargainAllDistributor',
      'bargainName',
      'bargainTag',
      'bargainGate',
      'bargainDate',
      'bargainIntegralDate',
      'bargainStoreNum',
      'stroeTypeList',
      'bargainLimiNum',
      'bargainUnLimitNum',
      'aFDList',
      'dFDList',
      'storeTypeLimitNumberDTOList',
      'bargainIsSet',
      'getCouponsData',
      'factoryMsgDTOList',
      'payDistributorIdList'
    ]),
    ...mapState([
      'bargain'
    ]),
    limitTypeEnum () {
      return this.$store.state.bargain.form.isCurrencyNum == '0' ? 'GENERAL_STORE' : 'STORE_TYPE'
    },
    exceptionalTypeEnum () {
      return this.$store.state.bargain.form.isStoreSet == '0' ? 'STORE' : 'DISTRIBUTOR'
    },
    timeList () {
      return [{
        startDatetime: formatDate(this.$store.state.bargain.form.date[0], true),
        endDatetime: formatDate(this.$store.state.bargain.form.date[1], true)
      }]
    },
    activeLimit () {
      return [{
        startDatetime: formatDate(this.$store.state.bargain.form.integralDate[0], true),
        endDatetime: formatDate(this.$store.state.bargain.form.integralDate[1], true)
      }
      ]
    },
    activeDelay () {
      return [{
        startDatetime: formatDate(this.$store.state.bargain.form.delayDate[0], true),
        endDatetime: formatDate(this.$store.state.bargain.form.delayDate[1], true)
      }
      ]
    }
  },
  methods: {
    getDetailData () {
      this.loading = true
      this.status = 'loading'
      this.$ajaxGet(`/activity/factory_info/detail/${this.$route.query.id}`).then(data => {
        this.loading = false
        this.status = 'pass'
        this.$store.commit('getBargainDetail', data)
        this.$store.dispatch('getDistributData', '1')
        // 当详情接口请求完成后再获取所有经销商数据
        this.$refs.edit.getDeptTreeData()
      }).catch(data => {
        this.loading = false
        this.status = 'error'
      })
    },
    onShowList (type) {
      let url = { name: 'sales/bargain/list', query: {} }
      let urlJson = '/activity/factory_info/save_base'
      let params = {
        activityInfoDTO: {
          activityName: this.$store.state.bargain.form.name, // 促销名称
          startDate: this.timeList[0].startDatetime,
          endDate: this.timeList[0].endDatetime,
          joinTypeEnum: 'PART',
          promotionTagId: this.$store.state.bargain.form.tag // 活动标签
        },
        activityFactoryInfoDTO: { // 经销商列表
          factoryDistributorList: this.aFDList,
          delayDistributorIdList: this.dFDList,
          warningQuantity: !this.bargainIsSet ? this.$store.state.bargain.form.warningQuantity : '',
          phoneList: !this.bargainIsSet ? this.$store.state.bargain.form.phoneList.map(item => {
            return item.value
          }) : [],
          activeLimitStartTime: this.activeLimit[0].startDatetime, //积分返利/优惠券限时
          activeLimitEndTime: this.activeLimit[0].endDatetime, //积分返利/优惠券限时结束
          activeDelayStartTime: this.activeDelay[0].startDatetime, //例外延时激活限时
          activeDelayEndTime: this.activeDelay[0].endDatetime, //例外延时激活限时
          advertisingSlogan: this.$store.state.bargain.form.propagate, // 宣传语
          // limitTypeEnum: this.limitTypeEnum,// 门店限购类型,0:通用门店限购, 1:按门店类型限购"
          // exceptionalTypeEnum: this.exceptionalTypeEnum,
          // commonLimitNumber: this.$store.state.bargain.form.limitNum, // 通用门店限购 空表示不限购
          // storeTypeLimitNumberDTOList: this.limitTypeEnum == 'STORE_TYPE' ? this.storeTypeLimitNumberDTOList : [], // 按门店类型限购数量
          distributorJoinTypeEnum: !this.allDistributor ? 'PART' : 'WHOLE', // WHOLE 全场参与 PART 部分参与
          isOpenMsg: this.$store.state.bargain.form.phoneRemind.allRemind, // 总的开启提醒信息按钮
          factoryMsgDTOList: this.factoryMsgDTOList,
          payMethodTypeEnumList: this.bargain.form.payMethodTypeEnumList, // 支付方式
          payDistributorJoinType: this.bargain.form.payDistributorJoinType, // 支付是否是全部经销商
          payDistributorIdList: this.payDistributorIdList, // 制定经销商
          isParcel: this.bargain.form.isParcel
        }
      }
      if (this.bargain.form.isParcel) {
        params.activityFactoryInfoDTO.parcelContent = {}
        params.activityFactoryInfoDTO.parcelContent.factoryParcelTypeEnum = this.bargain.form.parcelContent.factoryParcelTypeEnum
        if (this.bargain.form.parcelContent.factoryParcelTypeEnum === 'AMOUNT') {
          params.activityFactoryInfoDTO.parcelContent.amount = this.bargain.form.parcelContent.amount
        } else {
          params.activityFactoryInfoDTO.parcelContent.num = this.bargain.form.parcelContent.num
        }
      }
      if (this.$store.state.bargain.form.mainImg.length) {
        if (this.$store.state.bargain.form.mainImg[0].imgUrl.indexOf('http') !== -1) {
          params.activityFactoryInfoDTO.mainImg = this.$store.state.bargain.form.mainImg[0].imgUrl
        } else {
          params.activityFactoryInfoDTO.mainImg = preFixPath + this.$store.state.bargain.form.mainImg[0].imgUrl
        }
      } else {
        params.activityFactoryInfoDTO.mainImg = ''
      }
      if (this.$route.query.id) {
        url.query.id = this.$route.query.id
        urlJson = '/activity/factory_info/update_base'
        if (this.type) url.query.type = this.type
      }
      this.$refs.edit.$refs['form'].validate(valid => {
        if (valid) {
          // 是否有经销商
          if (this.bargainSelected.length || this.bargainAllDistributor) {
            if (this.$route.query.id) params.activityFactoryInfoDTO.activityId = this.$route.query.id
            if (this.$refs.edit.isShelf == 'ON') {
              this.$router.push(url)
              return
            }
            this.status = 'loading'
            this.$jsonPost(urlJson, params).then(data => {
              url.query.id = data
              this.status = 'pass'
              if (!this.$route.query.id) this.$router.replace({ name: 'sales/bargain/rules', query: { id: data } })
              // this.$router.push(url)
              // this.$refs.storeEdit.setShowMotal()
              this.$router.push({ name: 'sales/bargain/limit', query: { id: this.$route.query.id } })
            }).catch(data => {
              this.status = 'pass'
            })
          } else {
            this.$Notice.error({
              title: '请选择经销商'
            })
          }
        }
      })
    },
    jumpPrevPage () {
      this.$router.back()
    }
  },
  beforeRouteEnter (to, from, next) {
    /*
        1. 路由从不是下一页进入的都清空
        2. 路由从下一页进入并且有id就不刷新接口--保存信息
      */
    next(vm => {
      if (from.name !== 'sales/bargain/list') {
        vm.isEmpty = true
      } else {
        vm.isSave = false
      }
      if (vm.isEmpty) {
        vm.$store.commit('setBargainEmpty')
        vm.$refs.edit.$refs.form.resetFields()
      }
      if (!vm.id) {
        // 不是编辑时候 触发子组件获取经销商数据
        vm.$refs.edit.getDeptTreeData()
      }
      if (vm.id && vm.isSave) vm.getDetailData()
    })
  }

}
</script>

